package com.tuling.netty;

import com.tuling.netty.command.AuditCmd;
import com.tuling.netty.session.Session;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@SpringBootApplication
@RestController
@Slf4j
public class NettyApplication {
    public static void main(String[] args) {
        SpringApplication.run(NettyApplication.class, args);
    }

    @PutMapping("/send")
    public void send(String dockerId, String dockerIp, String content) {
        Session session = Session.getSession();
        List<Channel> channelList = session.getAll();
        content = StringUtils.defaultIfBlank(content, "默认内容");
        for (Channel channel : channelList) {
            AuditCmd auditCmd = new AuditCmd();

            auditCmd.setContent(content);
            System.out.println("发送消息给" + channel.remoteAddress());
            ChannelFuture future = channel.writeAndFlush(auditCmd);
            future.addListener((ChannelFutureListener) channelFuture ->
                    log.info("server push msg:[{}]", auditCmd.getContent()));
        }
    }
}
